var watty_cast=new Array();
var watty_cast_headings="<table id='watty_cast_headings' class='watty_cast_headings'><tr><td>Celebrity</td><td style='text-align:right'>Character</td></tr></table>";
var imdbLink="http://www.wattpad.com/search?q=";
var nocastMessage="Pick a cast for this story";
var addcastMessage="add a character";
var changecastMessage="change cast";
var errorMessage_actorempty="Choose someone to play this character";
var errorMessage_role="Enter a character";
var workCast=new Array();
var badActors=new Array();
var storyID=1102;
var maxNumCast=20;

$(document).ready(function() {
	$('#cast_edit_opts').css('visibility','visible');
});

function make_imdb_link(actor) {
	return actor+' <a class="watty_cast_actor" href="'+imdbLink+escape('starring+"'+actor.toLowerCase().replace(/ /g,'+')+'"')+'" target="_blank" rel="nofollow" onclick="window.open(this.href);return false"><img src="'+ASSET_HOST+'/image/link.gif" width="14" height="10"></a>';
}

function show_cast() {
	if ($("#watty_cast").length<0)
		return;
	var wattyHTML='';
	var editable=($("#addprompt").length>0?true:false); // if the user can add tags to the story, assume they can edit the story
	if (watty_cast==null||watty_cast.length<=0&&editable) {
		wattyHTML+="<div class='watty_cast_list'><center>"+nocastMessage+"</center></div>";
		if (editable) {
			wattyHTML+="<a href='#' class='watty_cast_add' onclick='add_cast();return false'>"+addcastMessage+"</a>";
			wattyHTML+="<a href='#' style='visibility:hidden' class='watty_cast_change' onclick='edit_cast();return false'>"+changecastMessage+"</a>";
		}
	}
	else {
		if (watty_cast.length>maxNumCast)
			watty_cast.splice(maxNumCast,watty_cast.length-maxNumCast);
		for (var i=0;i<watty_cast.length;i++) {
			wattyHTML+="<div class='watty_cast_list' style='height:30px'>";
			wattyHTML+="<table name='actor_role' style='width:100%'><tr style='vertical-align:middle'><td>"+make_imdb_link(watty_cast[i].actor)+"</td><td class='watty_cast_role'>as "+watty_cast[i].role+"</td></tr></table>";
			if (editable)
				wattyHTML+="<div class='watty_cast_edit'></div>";
			wattyHTML+="</div>";
		}
		if (editable) {
			wattyHTML+="<a href='#' class='watty_cast_add'"+(watty_cast.length>=maxNumCast?" style='visibility:hidden'":"")+" onclick='add_cast();return false'>"+addcastMessage+"</a>";
			wattyHTML+="<a href='#' class='watty_cast_change' onclick='edit_cast();return false'>"+changecastMessage+"</a>";
		}
	}
	$("#watty_cast").html(wattyHTML);
}

function disable_inputs() {
	$("#watty_cast").find("input").each(function() {
		$(this).attr('disabled','true');
	});
	$("#watty_cast").find("a[name=cast_del]").add("#watty_cast_add").each(function() {
		$(this).css('visibility','hidden');
	});
}

function enable_inputs() {
	$("#watty_cast").find("input").each(function() {
		$(this).removeAttr('disabled');
	});
	$("#watty_cast").find("a[name=cast_del]").add("#watty_cast_add").each(function() {
		$(this).css('visibility','visible');
	});
}

function get_l_item(pos) {
	return $($("#watty_cast").children("div.watty_cast_list")[pos]);
}

function hide_edit_cast() {
	$("body").children("div[id^=Autocomplete]").remove(); // clear the autocomplete objects
	show_cast();
}

function confirm_unlisted_actors() {
	var promptText="The following people aren't on our list:\n\n";
	for (var i=0;i<badActors.length;i++)
		promptText+=badActors[i]+'\n';
	promptText+="\nDo you still want to cast them in your story?";
	return confirm(promptText);
}

function set_cast() {
	if (badActors.length==0 || confirm_unlisted_actors()) {
		var p_data=new Object();
		p_data.data=(watty_cast.length>0?watty_cast:"");
		eval("$.post('apiv2/setcast?id="+String(storyID)+"',p_data,function(){hide_edit_cast();});");
	}
	else
		enable_inputs();
}

function check_actors(pos) {
	$.get("apiv2/getactors",{term:watty_cast[pos].actor},function(data) {
		var good=false;
		if (data==null||data.length<1)
			good=false;
		else {
			for (var i=0;i<data.length&&!good;i++) {
				if (data[i].toLowerCase()==watty_cast[pos].actor.toLowerCase()) {
					good=true;
					if (watty_cast[pos].actor!=data[i])
						watty_cast[pos].actor=data[i];
				}
			}
		}
		if (!good)
			badActors.push(watty_cast[pos].actor);
		if (pos+1<watty_cast.length)
			check_actors(pos+1);
		else
			set_cast();

	},'json');
}

function dynamic_change_cast(doFunc) {
	$(document).each(doFunc);
	var i;
	workCast=new Array();
	var actor_inps=$("#watty_cast").find("input[name=cast_actor]");
	actor_inps.each(function () {
		workCast.push({actor:$(this).val(),role:$("#"+$(this).attr('id').replace("actor","role")).val()});
	});
	hide_edit_cast();
	edit_cast();
	actor_inps=$("#watty_cast").find("input[name=cast_actor]");
	for (i=0;i<Math.min(actor_inps.length,workCast.length);i++) {
		if ($("#watty_cast_actor_inp_"+String(i)).length > 0) {
			$("#watty_cast_actor_inp_"+String(i)).val(workCast[i].actor);
			$("#watty_cast_role_inp_"+String(i)).val(workCast[i].role);
		}
	}
}

function save_cast() {
	var errorFlag=false;
	$("#watty_cast").find("span.watty_cast_error").hide();
	for (var pos=0;pos<watty_cast.length&&!errorFlag;pos++) {
		watty_cast[pos].actor=$("#watty_cast_actor_inp_"+String(pos)).val();
		watty_cast[pos].role=$("#watty_cast_role_inp_"+String(pos)).val();
		if (watty_cast[pos].actor==""||watty_cast[pos].role=="") {
			errorFlag=true;
			if (watty_cast[pos].actor=="")
				$('#watty_cast_error_'+String(pos)).html(errorMessage_actorempty);
			else
				$('#watty_cast_error_'+String(pos)).html(errorMessage_role);

			$('#watty_cast_error_'+String(pos)).show();
		}
	}
	if (! errorFlag) {
		disable_inputs();
		badActors = new Array();
		if (watty_cast.length>0)
			check_actors(0);
		else
			set_cast();
	}
}

function edit_cast() {
	if (watty_cast.length == 0)
		$("#watty_cast").children("div.watty_cast_list").remove();
	$("#watty_cast").prepend(watty_cast_headings);
	$("#watty_cast").children("a.watty_cast_add").remove();
	$("#watty_cast").children("a.watty_cast_change").remove();
	var l_item=$("#watty_cast").children("div.watty_cast_list").first();
	for (var pos=0;pos<watty_cast.length;pos++) {
		var div=l_item.children("div.watty_cast_edit").first();

		var divHTML="";
		divHTML+="<span class='watty_cast_error' id='watty_cast_error_"+String(pos)+"'></span>";
		divHTML+="<table class='watty_cast_edit_table'>";
		divHTML+="<tr><td><input class='inputbox' style='width:150px' id='watty_cast_actor_inp_"+String(pos)+"' name='cast_actor' maxlength='45' type='text' value=''></td>";
		divHTML+="<td>as</td>";
		divHTML+="<td><nobr><input class='inputbox' style='width:85px' id='watty_cast_role_inp_"+String(pos)+"' name='cast_role' maxlength='45' type='text' value=''> ";
		divHTML+="<a href='#' name='cast_del' onclick=\"dynamic_change_cast(function() {watty_cast.splice("+String(pos)+",1);get_l_item("+String(pos)+").remove();});return false\">[x]</a>";
		divHTML+="</nobr></td></tr></table>";

		div.html(divHTML);

		$("#watty_cast_actor_inp_"+String(pos)).val(watty_cast[pos].actor);
		$("#watty_cast_role_inp_"+String(pos)).val(watty_cast[pos].role);

		l_item=l_item.nextAll("div.watty_cast_list").first();
	}
	
	var buttonsHTML="";
	buttonsHTML+="<table id='watty_cast_buttons' class='watty_cast_edit_table' style='float:right;width:auto'><tr>";
	buttonsHTML+="<td><input type='button' id='watty_cast_save' value='Save' onclick='save_cast()'></td>";
	buttonsHTML+="<td><input type='button' id='watty_cast_cancel' value='Cancel'></td>";
	buttonsHTML+="</tr></table>";
	buttonsHTML+="<a href='#' style='"+(watty_cast.length>=maxNumCast?"visibility:hidden;":"")+"position:relative;top:4px;padding:6px;vertical-align:bottom' id='watty_cast_add' value='[+]' onclick=\"dynamic_change_cast(function() {watty_cast.push({actor:'',role:''});});return false\">[+]</a><br style='clear:both'>";
	$("#watty_cast").append(buttonsHTML);

	$("#watty_cast_cancel").click(function() {
		disable_inputs();
		$.get("apiv2/getcast",{id:storyID},function(data) {
			watty_cast=data;
			hide_edit_cast();
		},'json');
	});

	$("#watty_cast").find("input[name^=cast_]").each(function() {
		$(this).keyup(function(event) {
			if (event.which==13) //enter button pressed
				save_cast();
		});
	});

	$("#watty_cast").find("table[name|=actor_role]").hide();
	$("#watty_cast").find("div.watty_cast_edit").show();
	$("#watty_cast").children("div.watty_cast_list").each(function() {
		$(this).css("height","auto");
	});

	for (var i=0;i<watty_cast.length;i++)
		$('#watty_cast_actor_inp_'+String(i)).autocomplete({source:'apiv2/getactors'});

	return false;
}

function add_cast() {
	if (watty_cast==null||watty_cast.length<=0) { //if the cast is empty
		watty_cast=new Array();
		$("#watty_cast").children("div.watty_cast_list").remove();
	}
	var actor_role=new Object();
	actor_role.actor="";
	actor_role.role="";
	watty_cast.push(actor_role);
	show_cast();
	edit_cast();
	return false;
}
